package com.yanghui.dtracing.core;

import com.yanghui.dtracing.core.plugin.IClassEnhancePluginDefine;
import lombok.AllArgsConstructor;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.utility.JavaModule;

import java.util.List;

public class PluginInstrumentBoot {

    public static AgentBuilder enhance(PluginSearch pluginSearch, AgentBuilder agentBuilder){
        agentBuilder = agentBuilder.type(pluginSearch.buildMatch())
                    .transform(new Transform(pluginSearch))
        ;
        return agentBuilder;
    }

    @AllArgsConstructor
    private static class Transform implements AgentBuilder.Transformer{

        private PluginSearch pluginSearch;

        @Override
        public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader, JavaModule module) {
            List<IClassEnhancePluginDefine> classEnhancePluginDefineList = this.pluginSearch.find(typeDescription);
            DynamicType.Builder<?> newBuilder = builder;
            for(IClassEnhancePluginDefine define : classEnhancePluginDefineList){
                DynamicType.Builder<?> possibleNewBuilder = define.define(newBuilder,typeDescription,classLoader);
                if(possibleNewBuilder != null){
                    newBuilder = possibleNewBuilder;
                }
            }
            return newBuilder;
        }
    }
}
